package com.eco.fanliapp.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.eco.fanliapp.common.constant.WechatConfig;
import com.eco.fanliapp.vo.wechat.Content;
import com.eco.fanliapp.vo.wechat.Data;
import com.eco.fanliapp.vo.wechat.TemplateMessage;
import com.eco.fanliapp.vo.wechat.menu.TextMessage;
import com.thoughtworks.xstream.XStream;
import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 微信公众号工具类
 * @author zhuchao
 *
 */
public class WeixinUtil {

	/**
	 * 获取公众号access_token
	 * @return
	 * @throws ParseException
	 * @throws IOException
	 */
	public static String getAccessToken() throws IOException {
		String url = WechatConfig.ACCESS_TOKEN_URL.replace("APPID", WechatConfig.APPID).replace("APPSECRET", WechatConfig.APPSECRET);
		JSONObject jsonObject = doGetStr(url);
		String token = null;
		if(jsonObject!=null){
			token = jsonObject.getString("access_token");
		}
		return token;
	}

	/**
	 * 获取用户openId列表
	 * @param accessToken
	 * @return
	 */
	public static  List<String> getOpenIdList(String accessToken) throws IOException {
		String url = WechatConfig.OPENID_LIST_URL.replace("ACCESS_TOKEN",accessToken);
		JSONObject jsonObject = doGetStr(url);
		if(jsonObject!=null){
			JSONObject json = jsonObject.getJSONObject("data");
			String openid = json.getString("openid");
			List<String> list = JSONArray.parseArray(openid, String.class);
			return  list;
		}
		return null;
	}


	/**
	 * 获取用户信息
	 * @param accessToken
	 * @param openId
	 * @return
	 * @throws IOException
	 */
	public static JSONObject getUserInfo(String accessToken,String openId) throws IOException {
		String url = WechatConfig.USER_INFO_URL.replace("ACCESS_TOKEN",accessToken).replace("OPENID",openId);
		JSONObject jsonObject = doGetStr(url);
		if(jsonObject!=null){
			return jsonObject;
		}
		return null;
	}

	/**
	 * 发送模板消息
	 * @param accessToken
	 * @param content
	 * @return
	 * @throws IOException
	 */
	public static Boolean sendTemplateMessage(String accessToken, String content) throws IOException {
		//获得发送消息的url
		String url= WechatConfig.SEND_MESSAGE_URL.replace("ACCESS_TOKEN", accessToken);
		//调用接口进行发送
		JSONObject jsonObject = doPostStr(url, content);
		String errmsg = null;
		if(jsonObject != null){
			errmsg = jsonObject.getString("errmsg");
		}
		if(errmsg != null && "ok".equals(errmsg)){
			return true;
		}else {
			return  false;
		}
	}

	/**
	 * 封装消息实体
	 * @param openId
	 * @param templateId
	 * @param firstParam
	 * @param keyword1Param
	 * @param keyword2Param
	 * @param keyword3Param
	 * @param keyword4Param
	 * @param remarkParam
	 * @return
	 * @throws ParseException
	 * @throws IOException
	 */
	public static Map<String,String> handleMessage(String accessToken, String openId, String templateId, String firstParam, String keyword1Param,String keyword2Param,String keyword3Param, String keyword4Param, String remarkParam) throws ParseException, IOException {
		//获取accessToken
		//String accessToken = WeixinUtil.getAccessToken();
		//创建消息发送实体对象
		TemplateMessage template=new TemplateMessage();
		template.setTouser(openId);
		template.setTemplate_id(templateId);
		//设置模板标题
		Content first=new Content();
		first.setValue(firstParam);
		first.setColor("#436EEE");

		Content keyword1 = new Content();
		keyword1.setValue(keyword1Param);
		keyword1.setColor("#436EEE");

		Content keyword2 = new Content();
		keyword2.setValue(keyword2Param);
		keyword2.setColor("#436EEE");

		Content keyword3 = new Content();
		keyword3.setValue(keyword3Param);
		keyword3.setColor("#436EEE");

		Content keyword4 = new Content();
		keyword4.setValue(keyword4Param);
		keyword4.setColor("#436EEE");

		Content remark = new Content();
		remark.setValue(remarkParam);
		remark.setColor("#436EEE");

		Data data = new Data();
		data.setFirst(first);
		data.setKeyword1(keyword1);
		data.setKeyword2(keyword2);
		data.setKeyword3(keyword3);
		data.setKeyword4(keyword4);
		data.setRemark(remark);

		template.setData(data);
		String jsonString = JSON.toJSONString(template);
		Boolean aBoolean = WeixinUtil.sendTemplateMessage(accessToken, jsonString);

		//返回处理后的结果
		Map<String,String> result = new HashMap<>();
		result.put("newsContent",jsonString);
		result.put("result",aBoolean ? "true" : "false");

		return result;
	}


	/**
	 * URL编码（utf-8）
	 *
	 * @param source
	 * @return
	 */
	public static String urlEncodeUTF8(String source) {
		String result = source;
		try {
			result = URLEncoder.encode(source, "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return result;
	}


	/**
	 * get请求
	 * @param url
	 * @return
	 * @throws ParseException
	 * @throws IOException
	 */
	public static JSONObject doGetStr(String url) throws ParseException, IOException{
		DefaultHttpClient client = new DefaultHttpClient();
		HttpGet httpGet = new HttpGet(url);
		JSONObject jsonObject = null;
		HttpResponse httpResponse = client.execute(httpGet);
		HttpEntity entity = httpResponse.getEntity();
		if(entity != null){
			String result = EntityUtils.toString(entity,"UTF-8");
			jsonObject = JSONObject.fromObject(result);
		}
		httpGet.releaseConnection();
		return jsonObject;
	}

	/**
	 * POST请求
	 * @param url
	 * @param outStr
	 * @return
	 * @throws ParseException
	 * @throws IOException
	 */
	public static JSONObject doPostStr(String url,String outStr) throws ParseException, IOException{
		DefaultHttpClient client = new DefaultHttpClient();
		HttpPost httpost = new HttpPost(url);
		JSONObject jsonObject = null;
		httpost.setEntity(new StringEntity(outStr,"UTF-8"));
		HttpResponse response = client.execute(httpost);
		String result = EntityUtils.toString(response.getEntity(),"UTF-8");
		jsonObject = JSONObject.fromObject(result);
		httpost.releaseConnection();
		return jsonObject;
	}

	/**
	 * xml转为map
	 * @param request
	 * @return
	 * @throws DocumentException
	 * @throws IOException
	 */
	public static Map<String, String> xmlToMap(HttpServletRequest request ) throws DocumentException, IOException{
		Map<String,String> map = new HashMap<String, String>();

		SAXReader reader = new SAXReader();

		InputStream ins = request.getInputStream();
		Document doc = reader.read(ins);

		Element root = doc.getRootElement();
		List<Element> list = root.elements();
		for (Element e : list) {
			map.put(e.getName(), e.getText());
		}
		ins.close();
		return map;
	}

	/**
	 * TextMessage 对象转 xml
	 * @param textMessage
	 * @return
	 */
	public static String textMessageToXml(TextMessage textMessage){
		XStream xstream = new XStream();
		xstream.alias("xml", textMessage.getClass());
		return xstream.toXML(textMessage);

	}

	/**
	 * 封装内容，并转成xml
	 * @param toUserName
	 * @param fromUserName
	 * @param content
	 * @return
	 */
	public static String initText(String toUserName, String fromUserName, String content, String msgId){
		TextMessage text = new TextMessage();
		text.setFromUserName(toUserName);
		text.setToUserName(fromUserName);
		text.setMsgType(WechatConfig.MESSAGE_TEXT);
		text.setCreateTime(new Date().getTime());
		text.setContent(content);
		text.setMsgId(msgId);
		return textMessageToXml(text);
	}


}